package com.showsu.editor.manage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.showsu.editor.entity.bo.XhsAwemeLinkBaseInfo;
import com.showsu.editor.entity.doo.UserPrivilege;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.entity.po.TblUserPrivilege;
import com.showsu.editor.entity.remote.AwemeVideoDetail;
import com.showsu.editor.entity.remote.WhoseCardVideoDetailResp;
import com.showsu.editor.entity.vo.response.DouyinVO;
import com.showsu.editor.entity.vo.response.LiveImgVO;
import com.showsu.editor.entity.vo.response.XhsLiveVO;
import com.showsu.editor.enums.UserPrivilegeEnum;
import com.showsu.editor.enums.VipLevelEnum;
import com.showsu.editor.service.IUserPrivilegeService;
import com.showsu.editor.service.IXhsDewaterRecordService;
import com.showsu.editor.utils.*;
import com.showsu.editor.utils.aliyun.OssUtil;
import com.showsu.editor.utils.remote.SelfAPIUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 1:43 下午 2024/9/14
 * @Modified By:
 */
@Component
@Slf4j
public class DouYinBusinessManager {

    @Autowired
    private RemoteIntegrationUtil remoteIntegrationUtil;

    @Autowired
    private OssUtil ossUtil;





    public DouyinVO handleLiveImages(String source) {
        DouyinVO result = null;
        log.info(" handleLiveImages-stp1-请求参数:{}", source);
        String contentUrl = HttpClientUtil.extractUrl(source);
        if (StringUtils.isBlank(contentUrl)) return result;
        log.info(" handleLiveImages-stp2-处理后url:{}", contentUrl);
        String longUrl = getLongUrlFromSource(contentUrl);
        log.info(" handleLiveImages-stp3-处理后longUrl:{}", longUrl);
        String awemeId = getAwemeIdFromSource(longUrl);
        log.info(" handleLiveImages-stp4-处理后awemeId:{}", awemeId);
        if (StringUtils.isBlank(awemeId)) return result;
        WhoseCardVideoDetailResp detailResp = remoteIntegrationUtil.getDyAwemeDetailForLive(awemeId);
        result=new DouyinVO();
        //如果查询不到作品详情，通常是作品不存在或者下架了，下面的流程就不继续了
        if (detailResp == null || detailResp.getResult() == null) {
            return result;
        }
        result.setRequestSuccess(true);
        if( detailResp.getResult().getAweme_detail() == null){
            return result;
        }
        result.setShareUrl(source);
        AwemeVideoDetail awemeVideoDetail=detailResp.getResult().getAweme_detail();
        result.setRemark(awemeVideoDetail.getDesc());
        List<DouyinVO.LiveImageInfo> liveList=new ArrayList<>();
        //判断不是live多图
        if(CollectionUtils.isEmpty(awemeVideoDetail.getImages())){
            AwemeVideoDetail.Video videoInfo=awemeVideoDetail.getVideo();
            if(videoInfo!=null){
                String coverUrl=null;
                //返回原封面图
                if(videoInfo.getCover()!=null&&!CollectionUtils.isEmpty(videoInfo.getCover().getUrl_list())){
                    coverUrl=videoInfo.getCover().getUrl_list().get(videoInfo.getCover().getUrl_list().size()-1);
                }
                String videoUrl=this.getLiveVideoUrl(videoInfo);
                if(StringUtils.isNotBlank(videoUrl)){
                    //疑似是否动图的标记,所以加入live动图列表
                    if(awemeVideoDetail.getAnimated_image_info()!=null){
                        DouyinVO.LiveImageInfo liveImageInfo=new DouyinVO.LiveImageInfo();
                        liveImageInfo.setUrl(videoUrl);
                        liveImageInfo.setCover(coverUrl);
                        liveList.add(liveImageInfo);
                    }else{
                        result.setVideoUrl(videoUrl);
                        result.setOriginCover(coverUrl);
                    }
                }
            }
        }else{
            for(AwemeVideoDetail.Images liveImage:awemeVideoDetail.getImages()){
                AwemeVideoDetail.Images.VideoDTO liveVideoInfo=liveImage.getVideo();
                if(liveVideoInfo!=null){
                    DouyinVO.LiveImageInfo liveImageInfo=new DouyinVO.LiveImageInfo();
                    //返回原封面图
                    if(!CollectionUtils.isEmpty(liveImage.getUrlList())){
                        liveImageInfo.setCover(liveImage.getUrlList().get(liveImage.getUrlList().size()-1));
                    }
                    String videoUrl=this.getLiveVideoUrl(liveVideoInfo);
                    if(StringUtils.isNotBlank(videoUrl)){
                        liveImageInfo.setUrl(videoUrl);
                    }
                    liveList.add(liveImageInfo);
                }
            }
        }
        result.setLiveImages(liveList);
        return result;
    }

    //获取live视频
    private String getLiveVideoUrl(AwemeVideoDetail.Video liveVideoInfo){
        //获取live视频
        List<String> videoUrlList;
        if(liveVideoInfo.getPlay_addr()!=null&&!CollectionUtils.isEmpty(liveVideoInfo.getPlay_addr().getUrl_list())){
            videoUrlList=liveVideoInfo.getPlay_addr().getUrl_list();
        }else if(liveVideoInfo.getPlay_addr_h264()!=null&&!CollectionUtils.isEmpty(liveVideoInfo.getPlay_addr_h264().getUrl_list())){
            videoUrlList=liveVideoInfo.getPlay_addr_h264().getUrl_list();
        }else if(liveVideoInfo.getPlay_addr_lowbr()!=null&&!CollectionUtils.isEmpty(liveVideoInfo.getPlay_addr_lowbr().getUrl_list())){
            videoUrlList=liveVideoInfo.getPlay_addr_lowbr().getUrl_list();
        }else{
            videoUrlList=new ArrayList<>();
        }
        return getLiveVideoUrl(videoUrlList);
    }

    //获取live视频
    private String getLiveVideoUrl(AwemeVideoDetail.Images.VideoDTO liveVideoInfo){
        //获取live视频
        List<String> videoUrlList;
        if(liveVideoInfo.getPlayAddr()!=null&&!CollectionUtils.isEmpty(liveVideoInfo.getPlayAddr().getUrlList())){
            videoUrlList=liveVideoInfo.getPlayAddr().getUrlList();
        }else if(liveVideoInfo.getPlayAddrH264()!=null&&!CollectionUtils.isEmpty(liveVideoInfo.getPlayAddrH264().getUrlList())){
            videoUrlList=liveVideoInfo.getPlayAddrH264().getUrlList();
        }else if(liveVideoInfo.getPlayAddrLowbr()!=null&&!CollectionUtils.isEmpty(liveVideoInfo.getPlayAddrLowbr().getUrlList())){
            videoUrlList=liveVideoInfo.getPlayAddrLowbr().getUrlList();
        }else{
            videoUrlList=new ArrayList<>();
        }
        return getLiveVideoUrl(videoUrlList);
    }

    //获取live视频
    private String getLiveVideoUrl(List<String> videoUrlList){
        String videoUrl = null;
        //5. 优先取这个头的live视频文件https://api
        for(String url : videoUrlList){
            videoUrl=url;
            if(url.contains("://api")){
                break;
            }
        }
        return ossUtil.uploadHandleWaterDirFile2AliyunOss(videoUrl,
                Constant.dyAwemeLiveHandlePrefix + IdUtil.simpleUUID() + ".mp4");
    }

    /**
     * 通过作品链接获取作品长链接
     * @param contentUrl
     * @return
     */
    public String getLongUrlFromSource(String contentUrl) {
        if (StringUtils.isBlank(contentUrl)) {
            return null;
        }
        String redirectUrl = contentUrl;
        try {
            StringBuilder startCut = new StringBuilder();
            if (contentUrl.indexOf("/video/") > 0) {
                startCut.append("/video/");
            } else if (contentUrl.indexOf("/note/") > 0) {
                startCut.append("/note/");
            }
            //针对以下类型的链接的处理：6.99 QkP:/ 复制打开抖音，看看【凤凰WEEKLY的作品】# 母亲通过监控看到奶奶殴打孩子 # 热点知多少  https://www.iesdouyin.com/share/video/7220321836377148731/?region=CN&mid=7220321871206665018&u_code=17b7dj7lc&did=MS4wLjABAAAA28whu2l0069eCyGwbBpWlrcSFR1SuzmqGUtC0muH2E47xPi_6boBjK6qWzU3JfBU&iid=MS4wLjABAAAA8NgKgZHpBxMC9f84xRgyB5sKhkBIeTsVrhlhX4SECSgHaeRaXmJqrV6VYgbjsxmr&with_sec_did=1&titleType=title&from_ssr=1&utm_source=copy&utm_campaign=client_share&utm_medium=android&app=aweme
            if (StringUtils.isNotBlank(startCut) && ( contentUrl.contains(Constant.dyLinkPrefix1)||contentUrl.contains(Constant.dyLinkPrefix2))) {
                return redirectUrl;
            }
            //针对以下类型的链接的处理：3.89 GVl:/ 复制打开抖音，看看【新疆禁毒的作品】你以为的你以为，就是你以为的吗？新型毒品花样多，莫... https://v.douyin.com/AWr1ET9/
            if (StringUtils.isBlank(startCut) && contentUrl.contains(Constant.dyLinkPrefix)) {
                redirectUrl = HttpUtil.get(contentUrl, Constant.defaultTimeOut);
                redirectUrl = HttpClientUtil.extractUrl(redirectUrl);
                return redirectUrl;
            }
        } catch (Exception e) {
            log.error("DouYinBaseService.getLongUrlFromSource(String) error", e);
        }
        return redirectUrl;
    }

    /**
     * 通过作品链接获取作品id
     * @param contentUrl
     * @return
     */
    public String getAwemeIdFromSource(String contentUrl) {
        if (StringUtils.isBlank(contentUrl)) {
            return null;
        }
        String awemeId = null;
        try {
            StringBuilder startCut = new StringBuilder();
            if (contentUrl.indexOf("/video/") > 0) {
                startCut.append("/video/");
            } else if (contentUrl.indexOf("/note/") > 0) {
                startCut.append("/note/");
            }else if (contentUrl.indexOf("/share/slides/") > 0) {
                startCut.append("/share/slides/");
            }
            //针对以下类型的链接的处理：6.99 QkP:/ 复制打开抖音，看看【凤凰WEEKLY的作品】# 母亲通过监控看到奶奶殴打孩子 # 热点知多少  https://www.iesdouyin.com/share/video/7220321836377148731/?region=CN&mid=7220321871206665018&u_code=17b7dj7lc&did=MS4wLjABAAAA28whu2l0069eCyGwbBpWlrcSFR1SuzmqGUtC0muH2E47xPi_6boBjK6qWzU3JfBU&iid=MS4wLjABAAAA8NgKgZHpBxMC9f84xRgyB5sKhkBIeTsVrhlhX4SECSgHaeRaXmJqrV6VYgbjsxmr&with_sec_did=1&titleType=title&from_ssr=1&utm_source=copy&utm_campaign=client_share&utm_medium=android&app=aweme
            if (StringUtils.isNotBlank(startCut) && ( contentUrl.contains(Constant.dyLinkPrefix1)||contentUrl.contains(Constant.dyLinkPrefix2))) {
                String awemeIdFromSub = StringUtil.subStringFromHttpUrl(contentUrl, startCut.toString(), "?");
                awemeId = awemeIdFromSub.replace(startCut, "").replace("/", "");
                log.info("查询权重-获取awemeId-awemeId:{}", awemeId);
            }
            //针对以下类型的链接的处理：3.89 GVl:/ 复制打开抖音，看看【新疆禁毒的作品】你以为的你以为，就是你以为的吗？新型毒品花样多，莫... https://v.douyin.com/AWr1ET9/
            if (StringUtils.isBlank(startCut) && contentUrl.contains(Constant.dyLinkPrefix)) {
                String redirectUrl = HttpUtil.get(contentUrl, Constant.defaultTimeOut);
                if (redirectUrl.indexOf("/video/") > 0) {
                    startCut.append("/video/");
                } else if (redirectUrl.indexOf("/note/") > 0) {
                    startCut.append("/note/");
                }else if (contentUrl.indexOf("/share/slides/") > 0) {
                    startCut.append("/share/slides/");
                }
                if (StringUtils.isBlank(startCut)) {
                    return awemeId;
                }
                String awemeIdFromSub  = StringUtil.subStringFromHttpUrl(redirectUrl, startCut.toString(), "?");
                awemeId = awemeIdFromSub.replace(startCut, "").replace("/", "");
                log.info("查询权重-获取awemeId-awemeIdFromSub:{}-awemeId:{}", awemeIdFromSub, awemeId);
            }
        } catch (Exception e) {
            log.error("DouYinBaseService.getAwemeIdFromSource(String) error", e);
        }
        return awemeId;
    }
}
